package vzaar

import scala.collection.mutable.ArrayBuffer

/**
 * Utility class for handling common command line arguments.
 * 
 * @author Marc G. Smith
 */
class VzaarCommandLine(args:Array[String]) {
	
	/**
	 * Get the string for the common command line arguments.
	 */
	val CommonArguments =
		"[-debug] [-url <url>] [-oatoken <token>] [-oasecret <secret>]"
	
	/**
	 * Get the string for the common command line arguments help.
	 */
	val CommonArgumentsHelp = 
		"   -debug              " +
		"Turn on debug out\n" +
		"   -url <url>          " +
		"The API URL to use. Default is https://vzaar.com.\n" +
		"   -oatoken <token>    " +
		"The OAuth token. This is typically your vzaar user name.\n" +
		"   -oasecret <secret>  " +
		"The OAuth secret as generated by vzaar\n\n" +
		"   The debug, url, oatoken and oasecret can be \n" +
		"   configured to defaults in the vzaar-config.sh and\n" +
		"   vzaar-config.bat files. Using the command line\n" +
		"   will override these settings.\n"
		
	
	private var oauthToken:String = System.getenv("VZAAR_OAUTH_TOKEN")
	private var oauthSecret:String = System.getenv("VZAAR_OAUTH_SECRET")
	private var debug:Boolean = "true".equals(System.getenv("VZAAR_DEBUG"))
	private var url:String = System.getenv("VZAAR_URL")
 
	/**
	 * Arguments not processed in the order they were submitted.
	 */
	var remainingArgs:Array[String] = process;
	
	/**
	 * Create a Vzaar instance based on the authentication, url and debugging
	 * command line arguments or environment variables.
	 * 
	 * @return a Vzaar instance
	 */
	def createVzaar():Vzaar = {
		var vzaar:Vzaar = null
		
		if(url != null) {
			vzaar = new Vzaar(url, oauthToken, oauthSecret)
		}
		else {
			vzaar = new Vzaar(oauthToken, oauthSecret)
		}
		
		if(debug) {
			vzaar.setDebugStream(System.out)
		}
		
		return vzaar;
	}
	
	/**
	 * Process the command line arguments
	 */
	private def process() = {
		var unprocessedArgs = new ArrayBuffer[String]
		var i = 0;
		while(i < args.length) {
  			if(args(i).equals("-debug")) {
				debug = true;
			}
			else if(args(i).equals("-url")) {
				i += 1;
				url = args(i);
			}
			else if(args(i).equals("-oatoken")) {
				i += 1;
				oauthToken = args(i);
			}
			else if(args(i).equals("-oasecret")) {
				i += 1;
				oauthSecret = args(i+1);
			}
			else {
				unprocessedArgs.append(args(i));
			}
  			
  			i += 1;
		}
		
		unprocessedArgs.toArray;
	}
}
